import React,{useState,useEffect, useRef} from 'react';
import { DndContext, PointerSensor, closestCenter, useSensor, useSensors } from '@dnd-kit/core';
import type { DragEndEvent } from '@dnd-kit/core/dist/types/index';
import {
  SortableContext,
  arrayMove,
  horizontalListSortingStrategy,
  useSortable,
} from '@dnd-kit/sortable';
import type { FC } from 'react';
import type { InputRef } from 'antd';
import { Form, Input,Tag,Button,Space,Tooltip,theme } from 'antd';
import { PlusOutlined } from '@ant-design/icons';

type SpecListValue = {
    name?: string;
    sort?:number
}
type SpecListProps = {
    value?: Array<SpecListValue>;
    onChange?: (value: Array<SpecListValue>) => void;
}
type Item = {
    id: number;
    name: string;
};

type DraggableTagProps = {
    tag: Item;
};

type FieldType = {
    name?: string;
    subSpecList?: Array<object>[];
};
const DraggableTag: FC<DraggableTagProps> = ({tag,onChange}) => {
    const [tags,setTags]  = useState(tag);
    const [editInput, setEditInput] = useState(false);
    const [editInputValue, setEditInputValue] = useState(tags.name);
    const editInputRef = useRef<InputRef>(null);
    const { listeners, setNodeRef, transform, transition, isDragging } = useSortable({ id: tags.id });
    const commonStyle = {
        cursor: 'move',
        transition: 'unset', // Prevent element from shaking after drag
    };
    const tagInputStyle: React.CSSProperties = {
        width: 64,
        height: 22,
        marginInlineEnd: 8,
        verticalAlign: 'top',
    };
    const tagsRef = useRef(null)
    useEffect(() => {
        editInputRef.current?.focus();
    }, [editInputValue]);
    const handleClose = (removedTag: string) => {
        console.log(removedTag)
        onChange()
    };
    const handleEditInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        setEditInputValue(e.target.value);
    };
    const handleEditInputConfirm = () => {
        const newTags = tags;
        newTags.name = editInputValue;
        setTags(newTags);
        setEditInput(false);
        setEditInputValue(newTags.name);
    };
    const isLongTag = tags.name.length > 20
    const style = transform
    ? {
        ...commonStyle,
        transform: `translate3d(${transform.x}px, ${transform.y}px, 0)`,
        transition: isDragging ? 'unset' : transition, // Improve performance/visual effect when dragging
    }
        : commonStyle;
        const tagElem = (
            <Tag
                closable
                style={style} bordered={false} ref={setNodeRef} {...listeners}
                ref={tagsRef}
                onClose={(e) => {
                    console.log(e)
                    handleClose(tags.name)
                    e.preventDefault();
                    e.nativeEvent.stopImmediatePropagation();
                    e.stopPropagation();
                }}
                onMouseDown={e => { console.log(tagsRef.current.onClose());e.stopPropagation()}}
            >
                <span onDoubleClick={(e) => {
                        setEditInput(true);
                        e.preventDefault();
                    }}
                >
                    {isLongTag ? `${tags.name.slice(0, 20)}...` : tags.name}
                </span>
            </Tag>
        )
    return (
        // <Tag style={style} bordered={false} ref={setNodeRef} {...listeners}>
        //     {/* <Input placeholder="请输入" value={tag.name} /> */}
        //     {tag.name}
        // </Tag>
        <>
            {
                editInput ? 
                (<Input
                    ref={editInputRef}
                    size="small"
                    style={tagInputStyle}
                    value={editInputValue}
                    onChange={handleEditInputChange}
                    onBlur={handleEditInputConfirm}
                    onPressEnter={handleEditInputConfirm}
                />) : 
                isLongTag ? 
                    (<Tooltip title={tags.name}>
                        {tagElem}
                    </Tooltip>)
                    : (tagElem)
            }
        </>
    );
}
// const SpecList: React.FC<SpecListProps> = ({ value = [], onChange }) => {
//     const [data,setData] = useState(value) 
//     const onValueChange = (e: React.ChangeEvent<HTMLInputElement>,index:number) => {
//         let dataList = [...data]
//         dataList[index].name  = e.target.value
//         setData(dataList)
//         onChange?.(index,e.target.value);
//     };
//     return (
//         <>
//         <Space>
//             {
//                 data.map((r,index) => {
//                     return (
//                         <Input
//                             type="text"
//                             value={r.name}
//                             key={index}
//                             onChange={e=>onValueChange(e,index)}
//                             style={{ width: 100 }}
//                         />
//                     )
//                 })
//             }
//             </Space>
//         </>
//     )
// }

const EditSpec: React.FC = (props:any) => {
    const { info } = JSON.parse(JSON.stringify(props))
    const [form] = Form.useForm();
    const [items, setItems] = useState<Item[]>(info.subSpecList);
    form.setFieldsValue(info)
    const onFinish = (values: any) => {
        console.log(values);
    };
    const sensors = useSensors(useSensor(PointerSensor));
    const handleDragEnd = (event: DragEndEvent) => {
        const { active, over } = event;
        if (!over) return;
    
        if (active.id !== over.id) {
            setItems((data) => {
                const oldIndex = data.findIndex((item) => item.id === active.id);
                const newIndex = data.findIndex((item) => item.id === over.id);
                return arrayMove(data, oldIndex, newIndex);
            });
        }
    };
    const { token } = theme.useToken();
    const [inputVisible, setInputVisible] = useState(false);
    const [inputValue, setInputValue] = useState('');
    const inputRef = useRef<InputRef>(null);
    const tagInputStyle: React.CSSProperties = {
        width: 64,
        height: 22,
        marginInlineEnd: 8,
        verticalAlign: 'top',
    };
    const tagPlusStyle: React.CSSProperties = {
        height: 22,
        background: token.colorBgContainer,
        borderStyle: 'dashed',
    };
    useEffect(() => {
        if (inputVisible) {
            inputRef.current?.focus();
        }
    }, [inputVisible]);
    const showInput = () => {
        setInputVisible(true);
    };
    const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        setInputValue(e.target.value);
    };
    
    const handleInputConfirm = () => {
        if (inputValue && !items.map(r=>r.name).includes(inputValue)) {
            let data = {
                id:'',
                name: inputValue
            }
            setItems([...items, data])
        }
        setInputVisible(false);
        setInputValue('');
    };
    const deleteSubSpec = (index:number) => {
        console.log(items,index)
    }
    return (
        <Form
            name="info"
            form={form}
            labelCol={{ span: 6 }}
            wrapperCol={{ span: 18 }}
            style={{ maxWidth: 600 }}
            initialValues={{ remember: true }}
            onFinish={onFinish}
            autoComplete="off"
        >
            <Form.Item<FieldType>
                label="规格名称"
                name="name"
                rules={[{ required: true, message: 'Please input your username!' }]}
            >
                <Input/>
            </Form.Item>
            <Form.Item<FieldType> label="规格子项" name="subSpecList" style={{ marginBottom: 0 }}>
                <DndContext sensors={sensors} onDragEnd={handleDragEnd} collisionDetection={closestCenter}>
                    <SortableContext items={items} strategy={horizontalListSortingStrategy}>
                        {items.map((item,index) => (
                            <DraggableTag tag={item} key={item.id} onChange={deleteSubSpec(index)}/>
                        ))}
                    </SortableContext>
                </DndContext> 
                {inputVisible ? (<Input
                    ref={inputRef}
                    type="text"
                    size="small"
                    style={tagInputStyle}
                    value={inputValue}
                    onChange={handleInputChange}
                    onBlur={handleInputConfirm}
                    onPressEnter={handleInputConfirm}
                />
                ) : (
                <Tag style={tagPlusStyle} icon={<PlusOutlined />} onClick={showInput}>
                    New Tag
                </Tag>)
                }
            </Form.Item>
        </Form>
    );
};
export default EditSpec;